# -*- coding: utf-8 -*-
from subprocess import call
import sys
from shutil import rmtree
import tarfile
import os
from tempfile import mkdtemp
#以后应从中间层middleware中取出需要的数据
import am_dependent

py_command='python2.6'
software_dir=os.path.join(os.getcwd(),os.path.dirname(sys.argv[0]),'pkg')

pkg_deps = am_dependent.pkg_dependents
pkg_info = am_dependent.pkg_info


def detect_sys_version():
    """检查Python版本，如果版本过低则安装高版本的"""
    if sys.version[0:3] < '2.5':
        #安装新版本的函数
        print "Python version must be 2.5 or above."
        sys.exit()


def select_pkg():
    """提示输入要安装的包"""
    choices=raw_input("input the packages you want to install,(%s):" %(str(pkg_deps.keys())))
    for each in choices.split(' '):
        install_software(each,'src')


def detect_dependent(software):
    """检测依赖"""
    deps=[software,]

    for each in pkg_deps[software]['module']:
        try:
            #if each not in sys.modules:
            __import__(each)
        except Exception, e:
            print e
            deps.insert(0,each)
    return deps

#试试偏函数 from functools import partial
def install_software_src(software,source_name,source_type):
    """通过源代码方式安装软件"""
    if source_type == 'src':
        tar = tarfile.open(source_name,'r')

        tempdir=mkdtemp()
        tar.extractall(path=tempdir)

        source_dir = tempdir
        while True:
            dirname = os.listdir(source_dir)
            if len(dirname)==1:
                if os.path.isfile(os.path.join(source_dir,dirname[0])):
                    break
                else:
                    source_dir = os.path.join(source_dir,dirname[0])
            else:
                break
        os.chdir(source_dir)
        a = call([py_command, 'setup.py', 'install'])

        rmtree(tempdir)


def install_software(software,source_type):
    """安装软件的主程序，会调用各种安装方式的子程序"""
    try:
        deps = detect_dependent(software)
        for each in deps:
            source_name=os.path.join(software_dir,pkg_info[each][source_type][0])
            install_software_src(each,source_name,source_type)

    except Exception, e:
        print e


detect_sys_version()
select_pkg()
